import 'package:flutter/material.dart';
import 'package:vdrag_saas/Utils.dart';
import 'package:vdrag_saas/bus.dart';
import 'package:vdrag_saas/detail/http.dart';
import 'package:vdrag_saas/list/pages/app_bar/tag.dart';

class SearchTags extends StatefulWidget {
  Future<List<String>> Function(List<String> filter) onUpdate;
  SearchTags(this.onUpdate) : super(key: Global.searchTagKey);

  @override
  State<SearchTags> createState() => SearchTagState();
}

class SearchTagState extends State<SearchTags> {
  List<Tag> tags = [];
  Future<List<Tag>> futureTags = Future(() => []);
  List<String> selectedTags = [];

  @override
  void initState() {
    futureTags = requestTags();
    super.initState();
  }

  void onChange([Tag? tag]) async {
    if (tag != null) {
      if (tag.selected && !selectedTags.contains(tag.name)) {
        selectedTags.add(tag.name);
      } else if (!tag.selected && selectedTags.contains(tag.name)) {
        selectedTags.remove(tag.name);
      }
    }
    List<String> tagNames = await widget.onUpdate(selectedTags);
    // List<Tag>
    setState(() {
      for (var tag in tags) {
        if (tagNames.contains(tag.name)) {
          tag.uKey.currentState?.show();
        } else {
          tag.uKey.currentState?.hidden();
        }
      }
    });
    // Api.listProduct(selectedTags);
  }

  void clear() {
    setState(() {
      for (var tag in tags) {
        tag.uKey.currentState?.reset();
      }
      selectedTags.clear();
      widget.onUpdate([]);
    });
  }

  void onSelect(bool val) {}

  Future<List<Tag>> requestTags() async {
    dynamic responst = await Http().get('/api/tags?sort=index:asc');
    List<Map<String, dynamic>> items =
        List<Map<String, dynamic>>.from(responst['data'] ?? []);
    print('initlized tags');
    for (var item in items) {
      String name = item['attributes']['name'];
      GlobalKey<TagState> key = GlobalKey();
      tags.add(Tag(
        name,
        onChange: onChange,
        uKey: key,
      ));
    }
    return tags;
  }

  @override
  Widget build(BuildContext context) {
    bool isMobile = Utils.isMobile(context);
    double height = isMobile ? 36 : 45;
    double screenWidth = MediaQuery.of(context).size.width;
    double innerWidth = screenWidth - 24;
    double width = isMobile ? innerWidth : 730;
    return FutureBuilder(
        initialData: tags,
        future: futureTags,
        builder: (context, AsyncSnapshot<List<Tag>> snapshot) {
          List<Tag> appData = [];
          if (snapshot.connectionState == ConnectionState.done &&
              !snapshot.hasError) {
            appData = snapshot.data ?? [];
          }
          return Container(
            constraints: const BoxConstraints(maxWidth: 720),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Expanded(
                  child: Container(
                      height: height,
                      constraints: BoxConstraints(maxWidth: width),
                      child: SingleChildScrollView(
                        scrollDirection: Axis.horizontal,
                        child: Row(
                          children: appData,
                        ),
                      )),
                )
                // MoreButton(tags),
              ],
            ),
          );
        });
  }
}
